package mysql_sync

import (
	"context"
	grpcError "gc-rds-ha/internal/error"
	"os"
	"os/exec"
	"strings"

	"google.golang.org/grpc/status"

	log "github.com/sirupsen/logrus"
)

const (
	InstallLock  = "../../scripts/sh/source/install.lock"
	InstallShell = "../../scripts/sh/proxysql_install.sh"
)

func CheckAndInstall(ctx context.Context) error {
	if _, err := os.Stat(InstallLock); err != nil {
		if err = os.Chmod(InstallShell, 0755); err != nil {
			log.WithFields(log.Fields{
				"InstallShell": InstallShell,
			}).Error("CheckOrInstall error")
			return err
		}
		c := exec.CommandContext(ctx, InstallShell)
		s, err := c.CombinedOutput()
		if err != nil {
			log.WithFields(log.Fields{
				"InstallShell": InstallShell,
			}).Error("CheckOrInstall CombinedOutput error: ")
			return err
		}
		if !strings.Contains(string(s), "started") {
			log.WithFields(log.Fields{
				"InstallShell": InstallShell,
			}).Error("CheckOrInstall faild !")
			return status.Errorf(grpcError.ErrArgsInvalid, "CheckOrInstall faild !")
		}
		log.Infof("CheckOrInstall success !")
	}
	return nil
}

func BindVipToProxy() bool {
	return true
}
